package org.openslash.util;


import java.sql.ResultSet;
import java.sql.SQLException;

public class StandardResultList implements ResultList {

	private ResultSet rs;
	private boolean hasnext;
	private int cols = 0;
	public StandardResultList(ResultSet rs)
	{
		this.rs = rs;
		hasnext = false;
		try {
			cols = rs.getMetaData().getColumnCount();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public ResultRow getFirstRowAndClose() {
		ResultRow rr = null;

		try {
			if( rs.next() )
			{
				rr = new ResultRow(cols);
				for(int i = 1; i <= cols; ++i)
				{
					rr.addColumn(rs.getString(i));
				}
				
				rs.close();
			}
		} catch (SQLException e) {
			rr = null;
			e.printStackTrace();
		}

		return rr;
	}

	@Override
	public ResultRow getNextRow() {
		ResultRow rr = null;
		if( hasnext )
		{
			rr = new ResultRow(cols);
			try {
				for(int i = 1; i <= cols; ++i)
				{
					rr.addColumn(rs.getString(i));
				}
			} catch (SQLException e) {
				e.printStackTrace();
				try {
					rs.close();
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}
		return rr;
	}

	@Override
	public boolean hasNext() {
		try {
			hasnext = rs.next();
		} catch (SQLException e) {
			e.printStackTrace();
			hasnext = false;
			try {
				rs.close();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}
		return hasnext;
	}

	@Override
	public int getColumnCount() {
		return cols;
	}
}



